import { Request, Response, NextFunction } from 'express';
import logger from '../utils/logger';

/**
 * 异步错误处理器
 * 用于包装异步路由处理器，自动捕获错误
 */
export const asyncHandler = (fn: Function) => (req: Request, res: Response, next: NextFunction) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};

/**
 * 错误重试机制
 */
export const retry = async (
  fn: Function,
  retries: number = 3,
  delay: number = 1000
): Promise<any> => {
  try {
    return await fn();
  } catch (error) {
    if (retries > 0) {
      logger.warn(`操作失败，${delay}ms后重试，剩余重试次数: ${retries}`, error);
      await new Promise(resolve => setTimeout(resolve, delay));
      return retry(fn, retries - 1, delay * 2);
    }
    throw error;
  }
};

/**
 * 超时处理
 */
export const withTimeout = (fn: Function, timeout: number = 5000) => {
  return Promise.race([
    fn(),
    new Promise((_, reject) => 
      setTimeout(() => reject(new Error(`操作超时: ${timeout}ms`)), timeout)
    )
  ]);
};